/*
 * @Author: CPS
 * @Date: 2020-07-19 09:09:33
 * @Last Modified by:   CPS
 * @Last Modified time: 2020-08-05 17:30:57
 * @Projectname Electron-fileWatcher
 * @Filename readDocx.js
 */
'use strict'
// const path = require('path');
// const zip = require('adm-zip');

import path from 'path'
import zip from 'adm-zip'


/**
 * 读取 docx格式 当作zip进行获取
 *
 * @param      {<type>}        zipTar  The zip tar
 * @return     {(string|zip)}  { description_of_the_return_value }
 */
function readDocx(zipTar) {
  try {
    // 判断格式是否docx
    if (path.extname(zipTar).toLowerCase() !== '.docx') return

    // 使用zip读取docx到缓存
    let tmpZip = new zip(zipTar);

    // 是否成功读取
    if (!tmpZip) return

    // 创建匹配条件
    let res = {}
    let exp = {
      pages: /\<Pages>(\w+)<\/Pages>/, // 获取页码
      words: /\<Words>(\w+)<\/Words>/, // // 获取字数
      lines: /\<Lines>(\w+)<\/Lines>/, //获取行数
    }

    let wordApp = tmpZip.readAsText('docProps/app.xml');
    for (let eachExp in exp) {
      let expRes = wordApp.match(exp[eachExp]);
      // console.log(exp.eachExp)
      if (expRes) {
        if (expRes[1]) {
          res[eachExp] = expRes[1]
        }
      }
    }

    tmpZip = wordApp = null
    return res
  } catch (e) {
    console.log(zipTar + '可能被其他人打开中.')
    console.log(e)
  }
}

export default readDocx